// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import store from './store/index.js'
import axios from '@/api/index'
import VCharts from 'v-charts'

import * as sys from '@/api/base'

const numeral = require('numeral')

// 注册为全局属性
Vue.prototype.$axios = axios
Vue.prototype.$numeral = numeral
Vue.config.productionTip = false

// 引入 element-ui
Vue.use(ElementUI)

// 引入 v-charts
Vue.use(VCharts)

/* 每次路由前进行验证 */
router.beforeEach((to, from, next) => {
  if (to.meta.requireAuth === true) {
    sys.verify().then(resp => {
      // 认证成功
      let user = resp.data
      if (store.state.user === null) {
        store.commit('login', user)
      }
      const roleSet = new Set(to.meta.roles)
      for (var i = 0; i < user.roleList.length; i++) {
        if (roleSet.has(user.roleList[i])) {
          next()
          return
        }
      }
      // 无匹配角色，跳转至导航页
      next({path: '/index'})
    }).catch(_ => {
      // 未通过认证
      next({
        path: '/login',
        query: {
          redirect: to.fullPath
        }
      })
    })
  } else {
    // 无需认证
    next()
  }
})

/* eslint-disable no-new */
new Vue({
  el: '#app',
  render: h => h(App),
  router,
  store,
  components: {
    App
  },
  template: '<App/>'
})
